import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import router from '@/router'

const Request = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API + '/php-admin/public/', //接口统一域名
    timeout: 600000, //设置超时
    headers: {
        'Content-Type': 'application/json;charset=UTF-8;',
    },
})

//请求拦截器
Request.interceptors.request.use(
    (config) => {
        // 每次发送请求之前判断是否存在token，如果存在，则统一在http请求的header都加上token，不用每次请求都手动添加了
        const token = localStorage.getItem('token')
        token && (config.headers.Authorization = token)
        //若请求方式为post，则将data参数转为JSON字符串
        if (config.method === 'POST') {
            config.data = JSON.stringify(config.data)
        }
        return config
    },
    (error) =>
        // 对请求错误做些什么
        Promise.reject(error),
)

//响应拦截器
Request.interceptors.response.use(
    (response) => {
        if (response.headers.authorization != undefined) {
            localStorage.setItem('token', response.headers.authorization)
        }
        //响应成功
        return response.data
    },
    (error) => {
        //响应错误
        if (error.response && error.response.status) {
            if (error.response.headers.authorization != undefined) {
                localStorage.setItem('token', error.response.headers.authorization)
            }

            const message = error.response.data.message
            switch (message) {
                case 'The token is in blacklist.':
                    return ElMessage.error(message)
                case 'The token is in blacklist grace period list.':
                    return Request(error.response.config)// 请求重发
                case 'The token is expired.':
                    return ElMessage.error(message)
                case 'Must have token':
                    router.push({
                        name: 'Login',
                        query: {
                            redirect: router.currentRoute.value.fullPath
                        }
                    })
                    return ElMessage.error(message)
                default:
                    return ElMessage.error(message)
            }

        } else {
            console.log(error)
            ElMessage.error(error)
            return Promise.reject(error)
        }
    },
)

export default Request